//
//  Alerter.swift
//  icar
//
//  Created by gongkai on 15/3/30.
//  Copyright (c) 2015年 anytracking. All rights reserved.
//

import Foundation
import UIKit

/**
提示工具类
**/
class Hinter {
    private struct Instance {
        static var preAlerter:SweetAlert?//最近一次弹出框
        static var preToaster:MBProgressHUD?//
    }
    
    //MARK:弹出框
    class func alert(msg:String,style:AlertStyle)->SweetAlert{
        self.hideAlert()
        self.hideToast()
        return SweetAlert().showAlert("", subTitle: msg, style: style)
    }
    
    class func alert(msg:String)->SweetAlert{
        return self.alert(msg, style: AlertStyle.None)
    }

    //网络故障Alert
    class func netWorkTimeOutAlert()->SweetAlert{
        return self.alert("网络超时，请检查网络",style:.Error)
    }
    
    //隐藏上一次的Alert
    class func hideAlert(){
        if (Instance.preAlerter != nil) {//清除上一次弹出框
            Instance.preAlerter!.closeAlert(0)
            Instance.preAlerter = nil
        }
    }
    
    //MARK:提示
    class func toast(msg:String,var inView:UIView?,isLoading:Bool){
        self.hideAlert()
        self.hideToast()
        var progress:MBProgressHUD = MBProgressHUD()
        
        if(count(msg)>=30){
            progress.detailsLabelText = msg
        }else{
            progress.labelText = msg
        }
        if(!isLoading){
            progress.mode = MBProgressHUDMode.Text
            progress.hide(true, afterDelay: 3)//3秒隐藏
        }else{
            progress.hide(true, afterDelay: 10)//10秒隐藏
        }
        if(inView==nil){
            inView = UIApplication.sharedApplication().keyWindow
        }
        inView!.addSubview(progress)
        progress.show(true)
        Instance.preToaster = progress
    }
    
    class func toast(msg:String,inView:UIView){
        self.toast(msg, inView: inView,isLoading: false)
    }
    
    class func toast(msg:String){
        self.toast(msg, inView: nil,isLoading: false)
    }
    
    //加载数据Toast
    class func loadingToast(){
        self.loadingToast("正在获取数据...")
    }
    
    class func loadingToast(msg:String){
        self.toast(msg, inView: nil,isLoading: true)
    }
    
    //隐藏上一次的Toast
    class func hideToast(){
        if (Instance.preToaster != nil){
            Instance.preToaster?.removeFromSuperview()
            Instance.preToaster = nil
        }
    }}

//MARK: 快捷方法
extension String{
    func showToast(){
        Hinter.toast(self)
    }
    
    func showAlert(){
        Hinter.alert(self)
    }
}

extension NSString{
    func showToast(){
        Hinter.toast(self as String)
    }
    func showLoadingToast(){
        Hinter.loadingToast(self as String)
    }
    
    func showAlert(){
        Hinter.alert(self as String)
    }
}